<script setup>
// 搜索表单对象
import {onMounted, ref, watch} from "vue";
import {CirclePlus, Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {queryPageApi, addEmpApi, queryByIdApi, deleteEmpApi, updateEmpApi} from "@/api/emp"
import {queryAllApi as queryAllDept} from "@/api/dept"
import {ElMessage, ElMessageBox} from "element-plus";

const tableData = ref([])
const searchForm = ref({
  name: '',
  gender: '',
  date: [],
  beginTime: '',
  endTime: ''
})
const rules = ref({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 20, message: '用户名长度应在2到28个字符之间', trigger: 'blur'}],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 16, message: '姓名长度应在2到1g个字符之间', trigger: 'blur'}],
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur'}
  ]
})

const token = ref('')
// 页面加载完成之后执行搜索方法
onMounted(() => {
  search() // 页面加载完成之后执行搜索方法
  queryAllDeptData() // 查询所有部门列表数据
  getToken() // 获取本地缓存中的token
})
// 获取本地缓存中的token
const getToken = () => {
  const loginUser = JSON.parse(localStorage.getItem('loginUser'))
  if (loginUser && loginUser.token) {
    token.value = loginUser.token
  }
}
// 搜索
const search = async () => {
  const result = await queryPageApi(searchForm.value.name, searchForm.value.gender, searchForm.value.beginTime, searchForm.value.endTime, currentPage.value, pageSize.value)
  if (result.code) {
    tableData.value = result.data.rows
    total.value = result.data.total
  }
}
// 查询所有部门数据
const depts = ref([])
// 查询所有部门列表数据
const queryAllDeptData = async () => {
  const result = await queryAllDept()
  if (result.code) {
    depts.value = result.data
  }
}
// 重置
const clear = () => {
  searchForm.value = {
    name: '',
    gender: '',
    date: [],
    beginTime: '',
    endTime: ''
  }
}
// 监听日期数据变化,如果日期变化则自动赋值beginTime为date的第一个元素并且赋值end为date第二个元素
watch(() => searchForm.value.date, (newVal) => {
  if (newVal && newVal.length > 0) {
    searchForm.value.beginTime = newVal[0]
    searchForm.value.endTime = newVal[1]
  }
})
// 分页
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示多少条
const background = ref(true)
const total = ref(0) // 总条数
// 页展示记录数变化
const handleSizeChange = (val) => {
  search()
  // console.log(`${val} 条记录/页`)
}
// 页码事件
const handleCurrentChange = (val) => {
  search()
  // console.log(`${val} 页码`)
}
// 表单
//性别列表数据
const genders = ref([
  {name: '男', value: 1},
  {name: '女', value: 2},
])
//职位列表数据
const jobs = ref([
  {name: '班主任', value: 1},
  {name: '讲师', value: 2},
  {name: '学工主管', value: 3},
  {name: '教研主管', value: 4},
  {name: '咨询师', value: 5},
  {name: '其他', value: 6},
])
const dialogFormVisible = ref(false)
const dialogTitle = ref('新增员工')
const employeeFormRef = ref()

// 添加按钮点击事件
const add = () => {
  dialogFormVisible.value = true;
  dialogTitle.value = '新增员工';
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: [
      {
        company: '',
        job: '',
        beginTime: '',
        endTime: '',
        timeRange: []
      },
    ]
  }
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields() // 重置表单数据校验
  }
}
// 编辑按钮点击事件
const update = async (id) => {
  const result = await queryByIdApi(id)
  if (result.code) {
    dialogFormVisible.value = true;
    dialogTitle.value = '编辑员工';
    employee.value = result.data
    // 工作经历时间显示处理
    if (employee.value.exprList) {
      for (let i = 0; i < employee.value.exprList.length; i++) {
        const expr = employee.value.exprList[i];
        expr.timeRange = [expr.beginTime, expr.endTime]
      }
    }
  }
}
// 删除按钮点击事件
const delById = async (id) => {
  ElMessageBox.confirm('确定要删除该员工吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const result = await deleteEmpApi(id)
    if (result.code) {
      await search() // 重新搜索
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
// 编辑行数据
const editRow = () => {
  if (selectedIds.value.length !== 1) {
    ElMessage.warning('请选择一条记录')
    return;
  }
  // 获取选中的单行
  const row = selectedIds.value[0]
  debugger
  update(row)
}
// 批量删除
const del = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return;
  }
  ElMessageBox.confirm('确定要批量删除选中的员工吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const result = await deleteEmpApi(selectedIds.value)
    if (result.code) {
      await search() // 重新搜索
      ElMessage.success('批量删除成功')
    }else {
    ElMessage.error('批量删除失败')
  }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
// 保存员工
const save = async () => {
  await employeeFormRef.value.validate() // 表单校验
  if (!employeeFormRef.value.validate()) {
    ElMessage.error('表单校验失败')
    return;
  }
  // 保存员工信息,如果id有值则为更新操作，否则为新增操作
  let result;
  if (employee.value.id) {
    result = await updateEmpApi(employee.value)
  } else {
    result = await addEmpApi(employee.value)
  }
  if (result.code) {
    dialogFormVisible.value = false;
    await search() // 重新搜索
    ElMessage.success('保存成功')
  } else {
    ElMessage.error(result.message)
  }
}
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: [
    {
      company: '',
      job: '',
      beginTime: '',
      endTime: '',
      timeRange: []
    },
  ]
})
// 文件上传成功后回调
const handleAvatarSuccess = (res, file) => {
  employee.value.image = 'http://localhost:5173/' + res.data //得到后端响应的图片地址
  console.log(employee.value)
}
// 文件上传之前的校验
const beforeAvatarUpload = (file) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  } else if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}
// 添加工作经历
const addWorkExperience = () => {
  employee.value.exprList.push({
    company: '',
    job: '',
    beginTime: '',
    endTime: '',
    timeRange: []
  })
}
// 删除工作经历
const deleteWorkExpr = (index) => {
  employee.value.exprList.splice(index, 1)
}
const selectedIds = ref([]);
// 表格选择框变化事件
const handleSelectionChange = (selected) => {
  // 收集选中行的id数组赋值给selectedIds变量，用于批量删除操作
  selectedIds.value = selected.map(item => item.id)
}
// 监听工作经历数据变化,如果日期变化则自动赋值beginTime为timeRange的第一个元素并且赋值end为timeRange第二个元素
watch(() => employee.value.exprList, (newVal, oldValue) => {
  if (employee.value.exprList && employee.value.exprList.length > 0) {
    for (let i = 0; i < newVal.length; i++) {
      if (newVal[i].timeRange && newVal[i].timeRange.length > 0) {
        newVal[i].beginTime = newVal[i].timeRange[0]
        newVal[i].endTime = newVal[i].timeRange[1]
      }
    }
  }
}, {deep: true})
</script>

<template>
  <div>
    <h1>员工管理</h1>
  </div>
  <!-- 搜索表单 -->
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable/>
      </el-form-item>
      <el-form-item label="性别">
        <el-select
            v-model="searchForm.gender"
            placeholder="请选择"
            clearable
        >
          <el-option label="男" value="1"/>
          <el-option label="女" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间">
        <el-date-picker
            v-model="searchForm.date"
            type="daterange"
            range-separator="到"
            start-placeholder="开始日期"
            endTime-placeholder="结束日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>
        <el-button type="info" @click="clear">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 工具栏 -->
  <div class="toolbar">
    <el-button type="primary" @click="add">
      <el-icon>
        <CirclePlus/>
      </el-icon>
      新增员工
    </el-button>
    <el-button type="danger" @click="del">
      <el-icon>
        <Delete/>
      </el-icon>
      批量删除
    </el-button>
    <el-button type="warning" @click="editRow">
      <el-icon>
        <Edit/>
      </el-icon>
      修改
    </el-button>
<!--    <el-button type="success" @click="save">-->
<!--      <el-icon>-->
<!--        <Check/>-->
<!--      </el-icon>-->
<!--      保存-->
<!--    </el-button>-->
  </div>
  <!-- 表格 -->
  <div>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="60"/>
      <el-table-column prop="name" align="center" label="姓名"/>
      <el-table-column prop="gender" align="center" label="性别">
        <template #default="scope">
          <span v-if="scope.row.gender === 1">男</span>
          <span v-else>女</span>
        </template>
      </el-table-column>
      <el-table-column prop="image" align="center" label="头像">
        <template #default="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.image" fit="fill"/>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" align="center" label="所属部门"/>
      <el-table-column prop="job" align="center" label="职位">
        <template #default="scope">
          <span v-if="scope.row.job === 1">班主任</span>
          <span v-else-if="scope.row.job === 2">讲师</span>
          <span v-else-if="scope.row.job === 3">学工主管</span>
          <span v-else-if="scope.row.job === 4">教研主管</span>
          <span v-else-if="scope.row.job === 5">咨询师</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" align="center" label="入职日期"/>
      <el-table-column prop="updateTime" align="center" label="最后操作时间"/>
      <el-table-column align="center" label="操作">
        <!--  自定义模板,基于插槽实现 -->
        <template #default="scope">
          <el-button size="small" type="primary" @click="update(scope.row.id)">
            <el-icon>
              <Edit/>
            </el-icon>
            修改
          </el-button>
          <el-button size="small" type="danger" @click="delById(scope.row.id)">
            <el-icon>
              <Delete/>
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页条 -->
  <div>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50,75,100]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 弹出层 -->
  <!-- Dialog 对话框 -->
  <el-dialog :title="dialogTitle" v-model="dialogFormVisible">
    <el-form
        :model="employee"
        label-width="80px"
        ref="employeeFormRef"
        :rules="rules"
    >
      <!-- 基本信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="employee.username"
                placeholder="请输入员工用户名,2-20个字"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
                v-model="employee.name"
                placeholder="请输入员工姓名,2-10个字"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
                v-model="employee.gender"
                placeholder="请选择"
                style="width: 100%"
            >
              <el-option
                  v-for="(gender, index) in genders"
                  :key="index"
                  :label="gender.name"
                  :value="gender.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
                v-model="employee.phone"
                placeholder="请输入员工手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select
                v-model="employee.job"
                placeholder="请选择"
                style="width: 100%"
            >
              <el-option
                  v-for="(job, index) in jobs"
                  :key="index"
                  :label="job.name"
                  :value="job.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input
                v-model="employee.salary"
                placeholder="请输入员工薪资"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select
                v-model="employee.deptId"
                placeholder="请选择"
                style="width: 100%"
            >
              <el-option
                  v-for="(dept, index) in depts"
                  :key="index"
                  :label="dept.name"
                  :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
                style="width: 100%"
                v-model="employee.entryDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <!-- 上传文件
            action: 上传文件请求地址, element-plus封装的,没有经过request.js
            show-file-list: 展示上传过的文件列表,默认为true
            on-success: 文件上传成功的回调函数,返回一个对象（后端响应的数据)
            before-upload: 文件上传前的回调函数,做文件类型大小的校验
            -->
            <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :headers="{'token': token}"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <!-- 回显图片 -->
              <el-image v-if="employee.image" :src="employee.image" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工作经历" size="small">
            <el-button type="success" @click="addWorkExperience"
            >添加工作经历
            </el-button
            >
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 工作经历信息 -->
      <el-row
          v-for="(exp, index) in employee.exprList"
          :key="index"
          :gutter="10"
      >
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker
                v-model="exp.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                endTime-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input
                v-model="exp.company"
                placeholder="请输入公司名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" size="small" label-width="60px">
            <el-input v-model="exp.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteWorkExpr(index)"
            >- 删除
            </el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.toolbar {
  margin: 20px;
}
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>